function [Omega,omega,omega0,P,k]=QDF_Classifier_train(data_fold_path,rate);
%use the train data to get a QDF, we assume all pdf as Gauss, and prior
%equal
%data_fold_path:the fold path of training data and their label, such as '../data/'
%Omega:k x k
%omega:k x 10
%omaga0:1 x 10
%P:use PCA to reduce the dim, P is 784xk, and give a k-dim Gauss
%distribution.

%check the input
if ~ischar(data_fold_path)
    error('input args should be char array like ''../data/'' ');
    Omega=eye(28*28,28*28);
    omega=zeros(28*28,10);
    omega0=zeros(1,10);
    P=eye(28*28,28*28);
    return;
end
%read data
train_image_name='train-images.idx3-ubyte';
train_label_name='train-labels.idx1-ubyte';

train_image_full_path=strcat(data_fold_path,train_image_name);
train_label_full_path=strcat(data_fold_path,train_label_name);

images=loadMNISTImages(train_image_full_path);
labels=loadMNISTLabels(train_label_full_path);

%use label to classify data to 0-9
size_images=size(images);
classified_images=cell(10,1);
for i=1:size_images(2)
    index=uint32(labels(i))+1;
    classified_images{index}=[classified_images{index},images(:,i)];
end
%calculate the mean
images_mean=zeros(28*28,10);
for i=1:10
    images_mean(:,i)=mean(classified_images{i},2);
end
%----------------PCA-----------------
%use all image for PCA
mean_cov=cov(images.');
%use image_mean for PCA
%mean_cov=cov(images_mean.');
[mean_V,mean_D]=eig(mean_cov);
mean_D_diag=diag(mean_D);
mean_D_diag_sum=sum(mean_D_diag);

[mean_D_diag_Y,mean_D_diag_I]=sort(mean_D_diag,'descend');
mean_V=mean_V(:,mean_D_diag_I);

%reduce the dim
add=0;
k=0;
for i=1:size(mean_D_diag_Y,1)
    add = add+mean_D_diag_Y(i);
    if add >rate*mean_D_diag_sum
        mean_V=mean_V(:,1:i);
        k=i;
        break;
    end
end

%--------------------end PCA--------------
images_mean_k=mean_V.'*images_mean;

Omega=zeros(k,k,10);
omega=zeros(k,10);
omega0=zeros(1,10);
for i=1:10
    classified_images_k=mean_V.'*classified_images{i};
    images_cov=cov(classified_images_k.');
    images_cov_inv=images_cov\eye(size(images_cov));
    Omega(:,:,i)=-0.5*(images_cov_inv);
    omega(:,i)=images_cov_inv*images_mean_k(:,i);
    omega0(1,i)=-0.5*(transpose(images_mean_k(:,i))*omega(:,i))-0.5*log(det(images_cov));
end
P=mean_V;
end